import { ipcMain } from 'electron'
import * as cheerio from 'cheerio'
import ejs from 'ejs'
import fs from 'fs'
import pinyin from 'js-pinyin'
import prettier from 'prettier'

export const setupDomToTableHandlers = () => {
  ipcMain.handle('dom-to-table', (_event, richText: any) => {
    return new Promise(async (resolve) => {
      const tableConfig = getTableConfig(richText)
      console.log(tableConfig)
      const tableRes = await renderTable(tableConfig)
      const scriptRes = await renderScript(tableConfig)

      const res = {
        table: tableRes,
        script: scriptRes
      }
      resolve(res)
    })
  })
}

const renderTable = (tableConfig: any) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./src/main/handlers/domToTable/table.ejs', 'utf8', (err, template) => {
      if (err) {
        reject(err)
        console.error('Error reading template:', err)
        return
      }

      // 渲染模板，并传递变量
      const renderedTemplate = ejs.render(template, {
        tableConfig
      })

      const formattedTemplate = prettier.format(renderedTemplate, {
        parser: 'vue',
        printWidth: 120,
        tabWidth: 4,
        useTabs: true
      })

      resolve(formattedTemplate)
    })
  })
}

const renderScript = (tableConfig: any) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./src/main/handlers/domToTable/script.ejs', 'utf8', (err, template) => {
      if (err) {
        reject(err)
        console.error('Error reading template:', err)
        return
      }

      // 渲染模板，并传递变量
      const renderedTemplate = ejs.render(template, {
        tableConfig
      })

      const formattedTemplate = prettier.format(renderedTemplate, {
        parser: 'typescript',
        printWidth: 120,
        tabWidth: 4,
        useTabs: true
      })

      resolve(formattedTemplate)
    })
  })
}

const getTableConfig = (cleanHtml) => {
  const $ = cheerio.load(cleanHtml)
  const tableConfig: any = {
    columns: [],
    data: [],
    actionList: []
  }

  // 提取 columns，并记录非序号列的索引
  const colIndexMap: number[] = []
  $('.el-table__header thead tr th .cell').each(function (i) {
    const title = $(this).text().trim()
    if (title && title !== '序号') {
      tableConfig.columns.push({
        title,
        dataIndex: getPinYin(title),
        width: 80 + title.length * 14
      })
      colIndexMap.push(i)
    }
  })

  // 提取 data，只保留非序号列
  $('.el-table__body tbody tr').each(function () {
    const row: any = {}
    $(this)
      .find('td .cell')
      .each(function (index) {
        // 只处理非序号列
        const colMapIdx = colIndexMap.indexOf(index)
        if (colMapIdx !== -1) {
          const text = $(this).text().trim()
          const col = tableConfig.columns[colMapIdx]
          if (col) {
            row[col.dataIndex] = text
          }
        }
      })
    tableConfig.data.push(row)
  })

  return tableConfig
}

const getPinYin = (text: string) => {
  text = text.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')
  const str = pinyin.getCamelChars(text).toLowerCase()
  return `_temp_${str}`
}
